<template>
	<view class="container">
		<!-- 搜索框 -->
		<view class="search-bar">
			<view class="search-input-wrapper">
				<text class="search-icon">🔍</text>
				<input 
					class="search-input" 
					v-model="searchKeyword" 
					placeholder="搜索商品名称" 
					@input="onSearchInput"
				/>
				<text v-if="searchKeyword" class="clear-icon" @click="clearSearch">✕</text>
			</view>
		</view>
		
		<!-- 主要内容区域 -->
		<view class="main-content">
		<!-- 左侧分类列表 -->
		<view class="category-sidebar">
			<!-- 加载状态 -->
			<view v-if="loading" class="loading-container">
				<text class="loading-text">加载中...</text>
			</view>
			
			<!-- 空状态 -->
			<view v-else-if="flatCategories.length === 0" class="empty-container">
				<text class="empty-text">暂无分类</text>
			</view>
			
			<!-- 分类列表 -->
			<view 
				v-else
				class="category-item" 
				v-for="(category, index) in displayCategories" 
				:key="category.id || index"
				:class="{ 
					active: selectedCategoryId === category.id,
					'has-children': category.category && category.category.children && category.category.children.length > 0
				}"
				:style="{ paddingLeft: (category.level * 10 + 5) + 'px' }"
				@click="handleCategoryClick(category)"
			>
				<view class="category-content">
					<text class="category-name">{{ category.name }}</text>
					<view v-if="getCategoryCartCountByItem(category) > 0" class="cart-badge">
						<text class="badge-text">{{ getCategoryCartCountByItem(category) }}</text>
					</view>
				</view>
			</view>
		</view>
			
			<!-- 右侧商品区域 -->
			<view class="product-area" v-if="flatCategories.length > 0">
				<!-- 商品列表 -->
				<view class="product-list" v-if="getCurrentCategoryProducts().length > 0">
					<view 
						class="product-item" 
						v-for="(product, index) in getCurrentCategoryProducts()" 
						:key="index"
					>
						<image class="product-image" v-if="product.image" :src="product.image" mode="aspectFill"></image>
						<image class="product-image" style="border:1px solid #f0f0f0;" v-else src="../common/images/noImage.png" mode="aspectFill"></image>
						<view class="product-info">
							<text class="product-name">{{ product.name }}
								<text class="product-faceValue" v-if="product.faceValue">{{'/' +  product.faceValue }}</text>
							</text>
							<!--<text class="product-stats">已售{{ product.sold }}</text>-->
							<text class="product-stats">库存:{{ product.stock }}</text>
							<text class="product-costPrice" v-if="product.costPrice">¥{{ product.costPrice }}</text>
							<text class="product-price">¥{{ product.price }}
								<text class="product-specification" v-if="product.specification">/{{ product.specification }}</text>
							</text>
						</view>
						<view class="product-actions">
							<!-- 如果商品在购物车中，显示数量选择器 -->
							<view v-if="getProductCartCount(product.id) >= 0" class="quantity-selector">
								<view class="quantity-btn decrease" @click="decreaseQuantity(product.id)">
								</view>
								<input 
									class="quantity-input" 
									type="number" 
									v-model="inputValues[product.id]"
									@input="handleQuantityInput(product.id, $event)" 
									@blur="handleQuantityBlur(product.id)"
									:maxlength="getStockDigits(product.id)"
								/>
								<view class="quantity-btn increase" @click="increaseQuantity(product.id)">
								</view>
							</view>
							<!-- 如果商品售罄，显示售罄按钮 -->
							<view v-else-if="product.stock === 0" class="sold-out-btn">
								<text class="sold-out-text">已售罄</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 无分类时的提示 -->
		<view v-if="flatCategories.length === 0" class="no-category-tip">
			<text class="tip-text">暂无分类数据，请先添加分类</text>
		</view>
		
		<!-- 购物车结算栏 -->
		<view class="cart-bar" v-if="cartTotal > 0">
			<view class="cart-info" @click="showCartModal">
				<text class="cart-icon">
					<image src="../common/images/car1.png" mode="aspectFill"></image>
				</text>
				<text class="cart-total">¥{{ cartTotal }}</text>
			</view>
			<view class="checkout-btn" @click="goToCheckout">
				<text class="checkout-text">去结算</text>
			</view>
		</view>
		
		<!-- 底部导航栏 -->
		<view class="bottom-nav">
			<view class="nav-item active">
				<text class="nav-icon">
					<image src="../common/images/index2.png" mode="aspectFill"></image>
				</text>
				<text class="nav-label">首页</text>
			</view>
			<view class="nav-item" @click="goToShoppingCart">
				<text class="nav-icon">
					<image src="../common/images/car1.png" mode="aspectFill"></image>
				</text>
				<text class="nav-label">购物车</text>
				<view v-if="cartItemCount > 0" class="nav-badge">
					<text class="nav-badge-text">{{ cartItemCount }}</text>
				</view>
			</view>
			<view class="nav-item" @click="goToOrderList">
				<text class="nav-icon">
					<image src="../common/images/order1.png" mode="aspectFill"></image>
				</text>
				<text class="nav-label">订单</text>
			</view>
			<view class="nav-item" @click="goToShoppingOrderList">
				<text class="nav-icon">
					<image src="../common/images/order1.png" mode="aspectFill"></image>
				</text>
				<text class="nav-label">交款订单</text>
			</view>
		</view>
		
		<!-- 购物车弹窗 -->
		<view class="cart-modal" v-if="showCart" @click="hideCartModal">
			<view class="cart-content" @click.stop>
				<view class="cart-header">
					<text class="cart-title">已选商品</text>
					<text class="clear-btn" @click="clearCart">清空</text>
				</view>
				<view class="cart-list">
					<view 
						class="cart-item" 
						v-for="(item, index) in cartItems" 
						:key="index"
					>
						<view class="check-box" :class="{ active: item.selected }" @click="toggleItemSelection(item.id)">
							<text v-if="item.selected" class="check-icon">✓</text>
						</view>
						<image class="cart-item-image" :src="item.image" mode="aspectFill"></image>
						<view class="cart-item-info">
							<text class="cart-item-name">{{ item.name }}</text>
							<text class="cart-item-price">¥{{ item.price }}</text>
						</view>
						<view class="cart-quantity-selector">
							<view class="cart-quantity-btn decrease" @click="decreaseQuantity(item.id)">
							</view>
							<input
								class="cart-quantity-input"
								type="number"
								v-model="inputValues[item.id]"
								@input="handleQuantityInput(item.id, $event)"
								@blur="handleQuantityBlur(item.id)"
								:maxlength="getStockDigits(item.id)"
							/>
							<view class="cart-quantity-btn increase" @click="increaseQuantity(item.id)">
							</view>
						</view>
					</view>
				</view>
				<view class="cart-footer">
					<view class="cart-summary">
						<view class="check-box" :class="{ active: isAllSelected }" @click="toggleSelectAll">
							<text v-if="isAllSelected" class="check-icon">✓</text>
						</view>
						<text class="summary-text">合计: ¥{{ cartTotal }}</text>
					</view>
					<view class="cart-checkout-btn" @click="goToCheckout">
						<text class="cart-checkout-text">去结算</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 底部指示器 -->
		<view class="home-indicator"></view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			selectedCategory: 0,
			selectedCategoryId: null, // 选中的分类ID
			showCart: false,
			cart: {}, // 购物车数据 {productId: quantity}
			inputValues: {}, // v-model 绑定的输入缓存
			selectedItems: {}, // 选中的商品 {productId: true/false}
			categories: [], // 树形结构的分类数据
			flatCategories: [], // 扁平化的分类列表（用于显示和选择）
			loading: false,
			products: {}, // 改为空对象，从接口获取数据
			productsList: [], // 存储所有商品列表
			updateCartTimers: {}, // 防抖定时器对象 {productId: timer}
			expandedCategories: {}, // 展开状态：{ categoryId: true/false }
			searchKeyword: '' // 搜索关键词
		}
	},
	onLoad() {
		// 页面初始化，不在这里加载数据，统一在 onShow 中加载
	},
	onShow() {
		// 页面显示时加载数据（包括首次进入和从其他页面返回）
		this.loadCategories()
	},
	computed: {
		// 扁平化的分类列表（根据展开状态动态更新）
		displayCategories() {
			return this.renderTree(this.categories, 0)
		},
		// 当前选中的分类名称
		currentCategoryName() {
			const category = this.flatCategories.find(cat => cat.id === this.selectedCategoryId)
			return category ? category.name : '请选择分类'
		},
		cartItems() {
			const items = []
			for (let categoryProducts of Object.values(this.products)) {
				for (let product of categoryProducts) {
					if (this.cart[product.id] && this.cart[product.id] > 0) {
						items.push({
							...product,
							quantity: this.cart[product.id],
							selected: this.selectedItems[product.id] !== false // 默认为选中状态
						})
					}
				}
			}
			return items
		},
		cartTotal() {
			let total = 0
			for (let item of this.cartItems) {
				if (item.selected) {
					total += item.price * item.quantity
				}
			}
			return total
		},
		cartItemCount() {
			let count = 0
			for (let quantity of Object.values(this.cart)) {
				count += quantity
			}
			return count
		},
		isAllSelected() {
			if (this.cartItems.length === 0) return false
			return this.cartItems.every(item => item.selected)
		}
	},
	methods: {
		// 加载分类列表
		loadCategories() {
			this.loading = true
			
			// 使用新的 treeData 接口，返回的已经是树形结构
			this.$u.api.productCategory.treeData().then(res => {
				this.loading = false
				
				if (res && Array.isArray(res) && res.length > 0) {
					// treeData 接口直接返回树形结构数组
					this.categories = res || []
					// 初始时完全展开所有分类（扁平化所有数据）
					this.flatCategories = this.flattenTree(res)
					console.log('获取分类列表成功:', this.categories)
					console.log('扁平化分类列表:', this.flatCategories)
					
					// 如果没有选中的分类，默认选中第一个
					if (this.flatCategories.length > 0 && !this.selectedCategoryId) {
						this.selectedCategoryId = this.flatCategories[0].id
						this.selectedCategory = 0
					}
					
					// 加载分类成功后，加载商品列表
					this.loadProducts()
				} else if (res && res.list && res.list.length > 0) {
					// 兼容旧接口格式
					this.categories = res.list || []
					this.flatCategories = res.list || []
					// 加载分类成功后，加载商品列表
					this.loadProducts()
				} else {
					this.categories = []
					this.flatCategories = []
				}
			}).catch(err => {
				this.loading = false
				console.error('获取分类列表失败:', err)
				uni.showToast({
					title: '获取分类列表失败',
					icon: 'none'
				})
			})
		},
		
		// 将树形结构扁平化（用于显示和选择，根据展开状态）
		renderTree(nodes, level) {
			const result = []
			if (!nodes || nodes.length === 0) {
				return result
			}
			
			nodes.forEach(node => {
				result.push({
					id: node.id,
					name: node.name,
					parentCode: node.parentCode || '0',
					sort: node.sort,
					status: node.status,
					level: level,
					category: node // 保留原始节点引用
				})
				
				// 如果有子节点且已展开，递归渲染子节点
				if (node.children && node.children.length > 0 && this.expandedCategories[node.id]) {
					result.push(...this.renderTree(node.children, level + 1))
				}
			})
			return result
		},
		
		// 将树形结构完全扁平化（用于初始化和统计）
		flattenTree(tree, result = [], level = 0) {
			tree.forEach(node => {
				result.push({
					id: node.id,
					name: node.name,
					parentCode: node.parentCode || '0',
					sort: node.sort,
					status: node.status,
					level: level,
					category: node // 保留原始节点引用
				})
				if (node.children && node.children.length > 0) {
					this.flattenTree(node.children, result, level + 1)
				}
			})
			return result
		},
		
		// 加载商品列表
		loadProducts() {
			this.$u.api.productManagement.list().then(res => {
				if (res && res.list) {
					this.productsList = res.list || []
					console.log('获取商品列表成功:', this.productsList)
					
					// 将商品按分类ID分组
					this.organizeProductsByCategory()
				} else {
					this.productsList = []
					this.products = {}
				}
			}).catch(err => {
				console.error('获取商品列表失败:', err)
				uni.showToast({
					title: '获取商品列表失败',
					icon: 'none'
				})
			})
		},
		
		// 将商品按分类ID组织（包含子分类的商品）
		organizeProductsByCategory() {
			this.products = {}
			
			// 获取所有分类ID（包括子分类）
			const getAllCategoryIds = (categories) => {
				let ids = []
				categories.forEach(cat => {
					ids.push(cat.id)
					if (cat.children && cat.children.length > 0) {
						ids = ids.concat(getAllCategoryIds(cat.children))
					}
				})
				return ids
			}
			const allCategoryIds = getAllCategoryIds(this.categories)
			
			// 遍历所有商品，按分类ID分组
			this.productsList.forEach(product => {
				const categoryId = product.categoryId || product.category_id
				
				if (!this.products[categoryId]) {
					this.products[categoryId] = []
				}
				
				this.products[categoryId].push({
					id: product.id,
					name: product.name || '',
					image: product.image || '',
					sold: product.sold || 0,
					stock: product.stock || 0,
					price: product.price || 0,
					description: product.description || '',
					costPrice: product.costPrice || 0,
					specification: product.specification || '',
					faceValue: product.faceValue || ''
				})
			})
			
			console.log('商品分组结果:', this.products)
			
			// 商品加载完成后，加载购物车数据
			this.loadCartData()
		},
		
		// 切换展开/折叠
		toggleExpand(categoryId, event) {
			if (event) {
				event.stopPropagation()
			}
			this.$set(this.expandedCategories, categoryId, !this.expandedCategories[categoryId])
		},
		
		// 处理分类项点击（如果有子分类，先切换展开状态；然后选择分类）
		handleCategoryClick(category) {
			// 如果有子分类，先切换展开/折叠状态
			if (category.category && category.category.children && category.category.children.length > 0) {
				this.toggleExpand(category.id)
			}
			// 选择分类
			this.selectCategoryByItem(category)
		},
		
		// 加载购物车数据（回显）
		loadCartData() {
			this.$u.api.shopcart.list().then(res => {
				if (res && res.list) {
					// 清空现有购物车数据
					this.cart = {}
					this.inputValues = {}
					
					// 进入页面时，为所有商品初始化为 0，确保输入框显示 0
					if (Array.isArray(this.productsList) && this.productsList.length > 0) {
						this.productsList.forEach(p => {
							const pid = p && p.id
							if (pid != null) {
								this.$set(this.cart, pid, 0)
								this.$set(this.inputValues, pid, '0')
							}
						})
					}
					
					// 将服务器返回的购物车数据同步到本地
					res.list.forEach(item => {
						// 设置购物车数量
						this.$set(this.cart, item.productId, item.quantity || 0)
						this.$set(this.inputValues, item.productId, String(item.quantity || 0))
					})
					
					console.log('购物车数据回显成功:', this.cart)
					
					// 强制更新视图
					this.$forceUpdate()
				}
			}).catch(err => {
				console.error('获取购物车数据失败:', err)
				// 不显示错误提示，静默失败
			})
		},
		
		selectCategory(index) {
			// 兼容旧代码：通过索引选择
			this.selectedCategory = index
			if (this.flatCategories[index]) {
				this.selectedCategoryId = this.flatCategories[index].id
			}
		},
		
		selectCategoryByItem(category) {
			// 通过分类项直接选择
			this.selectedCategoryId = category.id
			// 在 flatCategories 中查找对应的索引
			const index = this.flatCategories.findIndex(cat => cat.id === category.id)
			if (index !== -1) {
				this.selectedCategory = index
			}
		},
		
		getCurrentCategoryProducts() {
			// 如果有搜索关键词，直接搜索所有商品
			if (this.searchKeyword && this.searchKeyword.trim()) {
				const keyword = this.searchKeyword.trim().toLowerCase()
				let allProducts = []
				
				// 遍历所有分类的商品
				for (let categoryProducts of Object.values(this.products)) {
					allProducts = allProducts.concat(categoryProducts)
				}
				
				// 根据商品名称过滤，并筛选掉库存为0的商品
				return allProducts.filter(product => {
					const matchName = product.name && product.name.toLowerCase().includes(keyword)
					return matchName && product.stock > 0
				})
			}
			
			// 根据当前选中的分类获取对应的商品列表（包含子分类的商品）
			if (!this.selectedCategoryId) {
				return []
			}
			
			// 在 flatCategories 中查找当前选中的分类
			const currentCategory = this.flatCategories.find(cat => cat.id === this.selectedCategoryId)
			if (!currentCategory) {
				return []
			}
			
			// 获取当前分类及其所有子分类的商品
			const getAllSubCategoryIds = (categoryNode) => {
				let ids = [categoryNode.id]
				if (categoryNode.children && categoryNode.children.length > 0) {
					categoryNode.children.forEach(child => {
						ids = ids.concat(getAllSubCategoryIds(child))
					})
				}
				return ids
			}
			
			// 从树形结构中查找对应的节点
			const findNodeInTree = (nodes, targetId) => {
				for (const node of nodes) {
					if (node.id === targetId) {
						return node
					}
					if (node.children && node.children.length > 0) {
						const found = findNodeInTree(node.children, targetId)
						if (found) {
							return found
						}
					}
				}
				return null
			}
			
			const categoryNode = findNodeInTree(this.categories, this.selectedCategoryId)
			if (!categoryNode) {
				// 如果找不到，只返回当前分类的商品
				const products = this.products[this.selectedCategoryId] || []
				// 筛选掉库存为0的商品
				return products.filter(product => product.stock > 0)
			}
			
			const allCategoryIds = getAllSubCategoryIds(categoryNode)
			
			// 合并所有相关分类的商品
			let allProducts = []
			allCategoryIds.forEach(id => {
				if (this.products[id]) {
					allProducts = allProducts.concat(this.products[id])
				}
			})
			
			// 筛选掉库存为0的商品
			return allProducts.filter(product => product.stock > 0)
		},
		onSearchInput() {
			// 搜索输入时的处理，可以在这里添加防抖等逻辑
		},
		clearSearch() {
			this.searchKeyword = ''
		},
		getProductCartCount(productId) {
			return this.cart[productId] || 0
		},
		getCategoryCartCount(categoryIndex) {
			// 兼容旧代码：通过索引获取
			if (!this.displayCategories[categoryIndex]) {
				return 0
			}
			return this.getCategoryCartCountByItem(this.displayCategories[categoryIndex])
		},
		
		getCategoryCartCountByItem(category) {
			// 通过分类项直接获取购物车数量
			let count = 0
			const categoryId = category.id
			
			// 获取当前分类及其所有子分类的商品
			const getAllSubCategoryIds = (categoryNode) => {
				let ids = [categoryNode.id]
				if (categoryNode.children && categoryNode.children.length > 0) {
					categoryNode.children.forEach(child => {
						ids = ids.concat(getAllSubCategoryIds(child))
					})
				}
				return ids
			}
			
			// 从树形结构中查找对应的节点
			const findNodeInTree = (nodes, targetId) => {
				for (const node of nodes) {
					if (node.id === targetId) {
						return node
					}
					if (node.children && node.children.length > 0) {
						const found = findNodeInTree(node.children, targetId)
						if (found) {
							return found
						}
					}
				}
				return null
			}
			
			const categoryNode = findNodeInTree(this.categories, categoryId)
			if (!categoryNode) {
				// 如果找不到，只统计当前分类的商品
				const categoryProducts = this.products[categoryId] || []
				for (let product of categoryProducts) {
					count += this.getProductCartCount(product.id)
				}
				return count
			}
			
			const allCategoryIds = getAllSubCategoryIds(categoryNode)
			
			// 统计所有相关分类的商品数量
			allCategoryIds.forEach(id => {
				const categoryProducts = this.products[id] || []
				for (let product of categoryProducts) {
					count += this.getProductCartCount(product.id)
				}
			})
			
			return count
		},
		
		increaseQuantity(productId) {
			console.log('增加商品数量:', productId)
			
			// 获取当前商品信息
			const product = this.productsList.find(p => p.id === productId)
			const currentQuantity = this.cart[productId] || 0
			const maxStock = Number(product.stock) || 0
			
			// 检查是否超过库存
			if (currentQuantity >= maxStock) {
				uni.showToast({
					title: `库存不足，最多只能选择${maxStock}件`,
					icon: 'none'
				})
				return
			}
			
			// 先更新本地购物车数据
			const newQuantity = currentQuantity + 1
			this.$set(this.cart, productId, newQuantity)
			this.$set(this.inputValues, productId, String(newQuantity))
			console.log('购物车状态:', this.cart)
			
			// 调用防抖更新接口
			this.updateCartDebounce(productId, newQuantity)
		},
		decreaseQuantity(productId) {
			console.log('减少商品数量:', productId)
			if (this.cart[productId] && this.cart[productId] > 0) {
				const newQuantity = this.cart[productId] - 1
				
				// 先更新本地购物车数据
				if (newQuantity === 0) {
					this.$delete(this.cart, productId)
					this.$set(this.inputValues, productId, '0')
				} else {
					this.$set(this.cart, productId, newQuantity)
					this.$set(this.inputValues, productId, String(newQuantity))
				}
				console.log('购物车状态:', this.cart)
				
				// 调用防抖更新接口
				this.updateCartDebounce(productId, newQuantity)
			}
		},
		
		// 防抖更新购物车接口
		updateCartDebounce(productId, quantity) {
			// 清除之前的定时器
			if (this.updateCartTimers[productId]) {
				clearTimeout(this.updateCartTimers[productId])
			}
			
			// 设置新的定时器，800ms后执行
			this.updateCartTimers[productId] = setTimeout(() => {
				this.updateCartToServer(productId, quantity)
			}, 800)
		},
		
		// 手动输入数量
		handleQuantityInput(productId, e) {
			// 使用事件中的最新值，避免与 v-model 同步顺序引发的读取旧值
			let val = (e && e.detail && e.detail.value != null) ? String(e.detail.value) : (this.inputValues[productId] != null ? String(this.inputValues[productId]) : '')
			// 仅保留数字
			val = val.replace(/[^\d]/g, '')
			let num = val === '' ? 0 : parseInt(val, 10)
			if (isNaN(num)) num = 0

			// 限制范围：0 - 库存
			const product = this.productsList.find(p => p.id === productId) || {}
			const maxStock = product && product.stock ? Number(product.stock) : 0
			if (num > maxStock) num = maxStock
			if (num < 0) num = 0
			
			// 回写到输入框，保证输入阶段也被夹紧显示
			this.$set(this.inputValues, productId, String(num))
			this.$set(this.cart, productId, num)
			this.updateCartDebounce(productId, num)
		},
		handleQuantityBlur(productId) {
			// 失焦时再次矫正空值
			let val = this.inputValues[productId] != null ? String(this.inputValues[productId]) : ''
			val = val.replace(/[^\d]/g, '')
			let num = val === '' ? 0 : parseInt(val, 10)
			if (isNaN(num)) num = 0
			
			const product = this.productsList.find(p => p.id === productId) || {}
			const maxStock = product && product.stock ? Number(product.stock) : 0
			if (num > maxStock) num = maxStock
			if (num < 0) num = 0
			
			this.$set(this.inputValues, productId, String(num))
			this.$set(this.cart, productId, num)
			this.updateCartDebounce(productId, num)
		},
		
		// 根据库存位数限制输入长度，减少大数瞬时输入
		getStockDigits(productId) {
			const product = this.productsList.find(p => p.id === productId) || {}
			const stock = product && product.stock ? Number(product.stock) : 0
			const digits = String(stock).length
			return digits > 0 ? digits : 3
		},
		
		// 更新购物车到服务器
		updateCartToServer(productId, quantity) {
			console.log('调用购物车接口:', { productId, quantity })
			
			this.$u.api.shopcart.updateCart({
				productId: productId,
				quantity: quantity
			}).then(res => {
				console.log('购物车更新成功:', res)
				if (res && res.result === 'true') {
					// 接口调用成功
					console.log('购物车同步成功')
				} else {
					// 接口调用失败，给出提示
					uni.showToast({
						title: res.message || '购物车更新失败',
						icon: 'none'
					})
				}
			}).catch(err => {
				console.error('购物车更新失败:', err)
				uni.showToast({
					title: '购物车更新失败，请重试',
					icon: 'none'
				})
			})
		},
		showCartModal() {
			this.showCart = true
		},
		hideCartModal() {
			this.showCart = false
		},
		clearCart() {
			// 确认清空购物车
			uni.showModal({
				title: '提示',
				content: '确定要清空购物车吗？',
				success: (res) => {
					if (res.confirm) {
						this.confirmClearCart()
					}
				}
			})
		},
		confirmClearCart() {
			// 调用清空购物车接口
			this.$u.api.shopcart.clear().then(res => {
				if (res && res.result === 'true') {
					// 清空本地购物车数据
					this.cart = {}
					this.selectedItems = {}
					this.$forceUpdate()
					this.showCart = false
					
					uni.showToast({
						title: '购物车已清空',
						icon: 'success'
					})
				} else {
					uni.showToast({
						title: res.message || '清空失败',
						icon: 'none'
					})
				}
			}).catch(err => {
				console.error('清空购物车失败:', err)
				uni.showToast({
					title: '操作失败，请重试',
					icon: 'none'
				})
			})
		},
		toggleItemSelection(productId) {
			console.log('切换商品选择状态:', productId, '当前状态:', this.selectedItems[productId])
			// 如果当前状态是undefined，说明是默认选中状态，应该设为false
			const currentState = this.selectedItems[productId] !== false
			this.$set(this.selectedItems, productId, !currentState)
			console.log('切换后状态:', this.selectedItems[productId])
		},
		selectAllItems() {
			for (let item of this.cartItems) {
				this.$set(this.selectedItems, item.id, true)
			}
		},
		unselectAllItems() {
			for (let item of this.cartItems) {
				this.$set(this.selectedItems, item.id, false)
			}
		},
		toggleSelectAll() {
			if (this.isAllSelected) {
				// 如果全部选中，则取消全选
				this.unselectAllItems()
			} else {
				// 如果有未选中的，则全选
				this.selectAllItems()
			}
		},
		goToCheckout() {
			// 只获取选中的商品
			const selectedItems = this.cartItems.filter(item => item.selected)
			
			if (selectedItems.length === 0) {
				uni.showToast({
					title: '请选择要购买的商品',
					icon: 'none'
				})
				return
			}
			
			uni.navigateTo({
				url: '/pages/inventoryManagement/confirmOrder?cart=' + JSON.stringify(selectedItems) + '&fromCart=true'
			})
		},
		goToShoppingCart() {
			uni.navigateTo({
				url: '/pages/inventoryManagement/shoppingCart'
			})
		},
		goToOrderList() {
			uni.navigateTo({
				url: '/pages/inventoryManagement/orderList'
			})
		},
		goToShoppingOrderList() {
			uni.navigateTo({
				url: '/pages/inventoryManagement/shoppingOrderList?byShop=1'
			})
		}
	},
	onBackPress() {
		// 拦截返回按钮，返回到首页
		uni.reLaunch({
			url: '/pages/sys/home/index4'
		})
		return true
	},
	onUnload() {
		// 页面卸载时清除所有定时器
		for (let productId in this.updateCartTimers) {
			if (this.updateCartTimers[productId]) {
				clearTimeout(this.updateCartTimers[productId])
			}
		}
	}
}
</script>

<style scoped>
.container {
	background-color: #ffffff;
	display: flex;
	flex-direction: column;
}

/* 搜索框 */
.search-bar {
	padding: 10px 15px;
	background-color: #ffffff;
	border-bottom: 1px solid #f0f0f0;
}

.search-input-wrapper {
	display: flex;
	align-items: center;
	background-color: #f5f5f5;
	border-radius: 20px;
	padding: 8px 15px;
}

.search-icon {
	font-size: 16px;
	color: #999999;
	margin-right: 8px;
}

.search-input {
	flex: 1;
	font-size: 14px;
	color: #333333;
	background-color: transparent;
}

.clear-icon {
	font-size: 14px;
	color: #999999;
	margin-left: 8px;
	padding: 2px 4px;
}

/* 主要内容区域 */
.main-content {
	flex: 1;
	display: flex;
	background-color: #ffffff;
	min-height: calc(100vh - 210px);
	max-height: calc(100vh - 210px);
	overflow: hidden;
}

/* #ifdef APP-PLUS */
.main-content {
	min-height: calc(100vh - 150px);
	max-height: calc(100vh - 150px);
}
/* #endif */

/* 左侧分类列表 */
.category-sidebar {
	width: 25%;
	background-color: #F6F6F6;
	border-right: 1px solid #f0f0f0;
	display: flex;
	flex-direction: column;
	overflow-y: auto;
	flex-shrink: 0;
}

.category-item {
	position: relative;
	padding: 20px 10px;
	border-bottom: 1px solid #f8f8f8;
}

.category-item.active {
	background-color: #fff;
	border-right: none;
	position: relative;
	z-index: 1;
	/* border-top-right-radius: 15px; */
	/* border-bottom-right-radius: 15px; */
	/* margin-right: -15px; */
}

.category-content {
	display: flex;
	align-items: center;
	justify-content: space-between;
	flex-direction: row;
}

.category-name {
	font-size: 12px;
	color: #333333;
	display: inline-block;
	white-space: nowrap;
	writing-mode: horizontal-tb;
	text-orientation: mixed;
}

.category-item.active .category-name {
	color: #ff4069;
	font-weight: 500;
}

.cart-badge {
	width: 16px;
	height: 16px;
	background-color: #ff4069;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
}

.badge-text {
	font-size: 10px;
	color: #ffffff;
	font-weight: bold;
}

/* 右侧商品区域 */
.product-area {
	flex: 1;
	background-color: #ffffff;
	padding: 10px;
	position: relative;
	margin-left: -1px;
	display: flex;
	flex-direction: column;
	overflow: hidden;
	min-width: 0;
}

/* 商品列表 */
.product-list {
	flex: 1;
	overflow-y: auto;
	min-height: 0;
	margin-bottom: 10px;
}

.product-item {
	display: flex;
	align-items: center;
	padding: 15px 0;
	border-bottom: 1px solid #f8f8f8;
}

.product-image {
	width: 60px;
	height: 60px;
	border-radius: 8px;
	margin-right: 10px;
	background-color: #f0f0f0;
}

.product-info {
	flex: 1;
}

.product-name {
	font-size: 14px;
	color: #000000;
	font-weight: bold;
	/* margin-bottom: 5px; */
	display: block;
}
.product-stats {
	font-size: 10px;
	color: #666666;
	/* margin-bottom: 8px; */
	display: block;
}
.product-costPrice {
	font-size: 10px;
	color: #666666;
	text-decoration: line-through;
	display: block;
}
.product-specification {
	font-size: 8px;
	line-height: 14px;
	color: #666666;
}
.product-price {
	font-size: 14px;
	color: #ff4069;
	font-weight: bold;
}

.product-actions {
	display: flex;
	align-items: center;
}

/* 添加按钮 */
.add-btn {
	width: 30px;
	height: 30px;
	background-color: #ff4069;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
}

.add-text {
	font-size: 18px;
	color: #ffffff;
	font-weight: bold;
}

/* 数量选择器 */
.quantity-selector {
	display: flex;
	align-items: center;
	gap: 8px;
}

.quantity-btn {
	width: 20px;
	height: 20px;
	background-color: #ff4069;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	position: relative;
}

.quantity-btn::before {
	content: '';
	position: absolute;
	width: 8px;
	height: 1px;
	background-color: #ffffff;
}

.quantity-btn.decrease::before {
	/* 减号就是一条横线，不需要额外样式 */
	display: block;
}

.quantity-btn.increase::after {
	content: '';
	position: absolute;
	width: 1px;
	height: 8px;
	background-color: #ffffff;
}

.quantity-number {
	font-size: 12px;
	color: #333333;
	font-weight: bold;
	min-width: 20px;
	text-align: center;
}

.quantity-input {
	width: 36px;
	height: 24px;
	line-height: 24px;
	background-color: #ffffff;
	border: 1px solid #f0f0f0;
	border-radius: 4px;
	text-align: center;
	font-size: 12px;
	color: #333333;
	font-weight: bold;
	padding: 0;
}

/* 售罄按钮 */
.sold-out-btn {
	padding: 6px 12px;
	background-color: #f0f0f0;
	border: 1px solid #e0e0e0;
	border-radius: 4px;
}

.sold-out-text {
	font-size: 12px;
	color: #999999;
}

/* 购物车结算栏 */
.cart-bar {
	position: fixed;
	bottom: 60px;
	left: 0;
	right: 0;
	height: 50px;
	background-color: #ffffff;
	border-top: 1px solid #f0f0f0;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 20px;
	z-index: 100;
}

.cart-info {
	display: flex;
	align-items: center;
	gap: 10px;
}

.cart-icon {
	font-size: 20px;
}

.cart-icon image {
	width: 25px;
	height: 25px;
}
.cart-total {
	font-size: 16px;
	color: #333333;
	font-weight: bold;
}

.checkout-btn {
	height: 35px;
	padding: 0 20px;
	background-color: #ff4069;
	border-radius: 18px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.checkout-text {
	font-size: 14px;
	color: #ffffff;
	font-weight: bold;
}

/* 底部导航栏 */
.bottom-nav {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 60px;
	background-color: #ffffff;
	border-top: 1px solid #f0f0f0;
	display: flex;
	z-index: 100;
}

.nav-item {
	flex: 1;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	position: relative;
}

.nav-icon {
	font-size: 20px;
	color: #666666;
	display: flex;
	align-items: center;
	justify-content: center;
}

.nav-icon image {
	width: 25px;
	height: 25px;
}

.nav-label {
	font-size: 12px;
	color: #666666;
}

.nav-item.active .nav-icon {
	color: #ff4069;
}

.nav-item.active .nav-label {
	color: #ff4069;
}

.nav-badge {
	position: absolute;
	top: 5px;
	right: 20px;
	width: 16px;
	height: 16px;
	background-color: #ff4069;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
}

.nav-badge-text {
	font-size: 10px;
	color: #ffffff;
	font-weight: bold;
}

/* 购物车弹窗 */
.cart-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: flex-end;
	z-index: 500;
}

.cart-content {
	width: 100%;
	background-color: #ffffff;
	border-radius: 20px 20px 0 0;
	max-height: 70vh;
	display: flex;
	flex-direction: column;
}

.cart-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20px;
	border-bottom: 1px solid #f0f0f0;
}


.cart-title {
	font-size: 18px;
	color: #333333;
	font-weight: bold;
}

.clear-btn {
	font-size: 16px;
	color: #007aff;
}

.cart-list {
	flex: 1;
	overflow-y: auto;
	padding: 0 20px;
}

.cart-item {
	display: flex;
	align-items: center;
	padding: 15px 0;
	border-bottom: 1px solid #f8f8f8;
}

.check-box {
	width: 20px;
	height: 20px;
	border: 2px solid #ccc;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 10px;
}

.check-icon {
	font-size: 12px;
	color: #fff;
	font-weight: bold;
}

.cart-item-image {
	width: 50px;
	height: 50px;
	border-radius: 8px;
	margin-right: 10px;
	background-color: #f0f0f0;
}

.cart-item-info {
	flex: 1;
}

.cart-item-name {
	font-size: 14px;
	color: #333333;
	font-weight: bold;
	margin-bottom: 5px;
	display: block;
}

.cart-item-price {
	font-size: 14px;
	color: #ff4069;
	font-weight: bold;
}

.cart-quantity-selector {
	display: flex;
	align-items: center;
	gap: 8px;
}

.cart-quantity-btn {
	width: 20px;
	height: 20px;
	background-color: #ff4069;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	position: relative;
}

.cart-quantity-btn::before {
	content: '';
	position: absolute;
	width: 8px;
	height: 1px;
	background-color: #ffffff;
}

.cart-quantity-btn.decrease::before {
	/* 减号就是一条横线，不需要额外样式 */
	display: block;
}

.cart-quantity-btn.increase::after {
	content: '';
	position: absolute;
	width: 1px;
	height: 8px;
	background-color: #ffffff;
}

.cart-quantity-number {
	font-size: 12px;
	color: #333333;
	font-weight: bold;
	min-width: 20px;
	text-align: center;
}

.cart-quantity-input {
	width: 36px;
	height: 24px;
	line-height: 24px;
	background-color: #ffffff;
	border: 1px solid #f0f0f0;
	border-radius: 4px;
	text-align: center;
	font-size: 12px;
	color: #333333;
	font-weight: bold;
	padding: 0;
}

.cart-footer {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20px;
	border-top: 1px solid #f0f0f0;
}

.cart-summary {
	display: flex;
	align-items: center;
	gap: 8px;
}

.check-box.active {
	background-color: #ff4069;
	border: 2px solid #ff4069;
}

.summary-text {
	font-size: 16px;
	color: #ff4069;
	font-weight: bold;
}

.cart-checkout-btn {
	height: 40px;
	padding: 0 30px;
	background-color: #ff4069;
	border-radius: 20px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.cart-checkout-text {
	font-size: 16px;
	color: #ffffff;
	font-weight: bold;
}

/* 加载状态 */
.loading-container {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 40px 15px;
}

.loading-text {
	color: #999999;
	font-size: 12px;
}

/* 空状态 */
.empty-container {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 40px 15px;
}

.empty-text {
	color: #999999;
	font-size: 12px;
}

/* 无分类提示 */
.no-category-tip {
	flex: 1;
	display: flex;
	justify-content: center;
	align-items: center;
	background-color: #ffffff;
}

.tip-text {
	color: #999999;
	font-size: 14px;
}

/* 底部指示器 */
.home-indicator {
	position: fixed;
	bottom: 10px;
	left: 50%;
	transform: translateX(-50%);
	width: 40px;
	height: 4px;
	background-color: #000000;
	border-radius: 2px;
}
</style>
